import os
import random
import streamlit as st

import config
import utils

@utils.exception_handler
def main():
    config.page_config("")  # 将 page_config 移动到函数开头
    name = st.query_params.get("name", default="")  # 显式指定默认值
    if name == "":
        st.title("文章列表")
        files_dict = {}
        folder_path = "./pages/article"
        # 遍历文件夹中的所有项
        file_names = [
            filename for filename in os.listdir(folder_path) if filename.endswith(".md")
        ]  # 检查是否为.md文件
        file_names.sort()  # 对文件名进行排序

        # 将排序后的文件名及其完整路径添加到字典中
        for filename in file_names:
            full_path = os.path.join(folder_path, filename)  # 获取文件的完整路径
            files_dict[filename.split(".")[0]] = full_path  # 将完整路径添加到字典中

        # 添加新的 div 结构
        for filename, full_path in files_dict.items():
            with open(full_path, mode="r", encoding="utf-8") as f:
                content = f.read()
                # 假设摘要在文件的前 50 个字符内
                summary = content[:50] + "..." if len(content) > 100 else content
            with st.container(border=True):
                col1, col2 = st.columns([1, 2])
                with col1:
                    # 随机图片
                    st.image(f"https://t.alcy.cc/moez", use_column_width=True)
                with col2:
                    st.markdown(f"## [{filename}](./Articles?name={filename})")  # 使用固定 URL 替换 st.session_state.url
                    st.code(summary)

    else:
        with open(f"./pages/article/{name}.md", mode="r", encoding="utf-8") as f:
            st.markdown(f.read())
        
        if st.page_link("./pages/Articles.py", label="返回文档目录", icon="📄"):
            st.query_params.clear()
            
if __name__ == "__main__":
    main()